#pragma once


#include "CommonHeads.h"
#ifdef _DEBUG
#define D3D_DEBUG_INFO
#endif
#include <d3dx9.h>
#include "ResourceFactory.h"
#include "InputHID.h"
#include "D3DXTypedefs.h"

#include "ResSprite.h"
#include "ResText.h"
#include "ResBitmapText.h"
#include "ResBitmapFont.h"
#include "OpenALWrapper.h"
#include "SoundSource.h"


#include "Log.h"


class CD3D9Engine: public ICompHandler
{
	protected:
		HWND		_hwnd;

	private:
		HINSTANCE	_hInst;
		HDC			_hdc;
		int			_winWidth;
		int			_winHeight;
		char*		_title;
		bool		_fullscr;
		bool		_isRunning;
		bool		_appActive;
		bool		_engineInited;
		bool		_console;
		bool		_isSceneBegun;

		D3DPRESENT_PARAMETERS	_pp;

		IDirect3D9*			_d3d9;
		IDirect3DDevice9*	_d3dDev;

		CResourceFactory*	_resFactory;
		CInputHID*			_input;

		COpenAL*			_sound;

		static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
		LRESULT RealWndProc(UINT msg, WPARAM wParam, LPARAM lParam);

		void ToggleFullscreen();

		void ClearBuffers();
		void ReleaseEngine();

		bool InitExternal();


	public:
		CD3D9Engine();
		~CD3D9Engine();

		//--------------------------------
		bool CreateEngineApp(char* title, int w, int h, bool fullscr);
		bool IsRunning() const { return _isRunning; }
		bool IsSceneBegun() const { return _isSceneBegun; }
		bool Idle();

		//--------------------------------
		CResourceFactory*		GetResourceFactory() const { return _resFactory; }
		CResourceSprite*		CreateSprite(const char* file, int width = 0, int height = 0, DWORD colorKey = XRGB(255, 0, 255));
		CResourceText*			CreateText(const char* font, int size = 10, bool bold = false, bool italic = false, bool underline = false);
		CResourceBitmapFont*	CreateBitmapFont(const char* fontTexture, int texWidth, int texHeight, int fontWidth, int fontHeight, DWORD colorKey = XRGB(255, 0, 255), const char *_fontCSVFile = NULL);
		CResourceBitmapText*	CreateBitmapText(const char* text, CResourceBitmapFont* srcBitmapFont, DWORD color = D3DCOLOR_XRGB(255,255,255));
		CResourceSoundSource*	CreateSoundSource(const char* file, SND_FILETYPE fileType);

		bool RemoveResource(IResourceObject* objRemove, bool forceRelease);


		//--------------------------------
		void BeginScene(bool clear, int lockFrame = 0);
		void EndScene();


		void Render(IRenderable* renderableObject, D3DXMATRIX* transform);


		LPDIRECT3DDEVICE9	GetDevice() const { return _d3dDev; }
		CInputHID*			GetInput() const { return _input; }
		COpenAL*			GetSoundAPI() const { return _sound; }
		int					GetWindowWidth() const { return _winWidth; }
		int					GetWindowHeight() const { return _winHeight; }

		void SetWindowCaption(char* txt) { if(txt != NULL) { SetWindowText(_hwnd, txt); }}
		bool ShowConsole(bool state);
};